/**
 * Copyright (C), 2020, JieYi Software System Co., Ltd.
 * All rights reserved.
 * FileName:       ExcuteAndShowController.java
 *
 * @Description:
 * @author: feiwe
 * Modification History:
 * Date         Author        Version        Discription
 * -------------------------------------------------------
 * 2020/11/9      feiwe                         add
 */


package com.fengwei.controller;

import cn.hutool.system.SystemUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengwei.executor.MysqlExecutor;
import com.fengwei.form.MapForObject.MapForObject;
import com.fengwei.form.MdmsUser;
import com.fengwei.requestdata.excuteAndShow.ExcuteAndShowAddCommonSqlData;
import com.fengwei.requestdata.excuteAndShow.ExcuteAndShowDelCommonSqlData;
import com.fengwei.requestdata.excuteAndShow.ExcuteAndShowEditCommonSqlData;
import com.fengwei.requestdata.excuteAndShow.ExcuteAndShowExecSqlData;
import com.fengwei.requestdata.excuteAndShow.ExcuteAndShowExportDataData;
import com.fengwei.requestdata.excuteAndShow.ExcuteAndShowGetCommonSqlData;
import com.fengwei.requestdata.excuteAndShow.ExcuteAndShowPagingListData;
import com.fengwei.service.ConsoleCommonService;
import com.fengwei.service.ExcuteAndShowService;
import com.fengwei.util.PltResult;
import com.fengwei.util.ResponseUtil;
import com.fengwei.verify.Verify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Controller
public class ExcuteAndShowController {
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private MysqlExecutor mysqlExecutor;

    @Autowired
    private ConsoleCommonService consoleCommonService;

    @Autowired
    private ExcuteAndShowService excuteAndShowService;

    @GetMapping(value = "/excuteAndShow/loadPage")
    public String loadPage(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        return "excuteAndShow";
    }

    /**
     * 执行SQL
     */
    @PostMapping(path = "/excuteAndShow/execSql")
    @ResponseBody
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public Map<String, Object> execSql(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        MdmsUser mdmsUser = consoleCommonService.checkAndGetUser(request);

        ExcuteAndShowExecSqlData excuteAndShowExecSqlData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(),
                new TypeReference<ExcuteAndShowExecSqlData>() {
                });

        // 校验传入参数
        Verify.verifyData(excuteAndShowExecSqlData);

        // 正式处理业务
        Map<String, Object> data = excuteAndShowService.execSql(excuteAndShowExecSqlData, request, mdmsUser);
        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

    /**
     * 执行SQL完SQL之后的分页
     */
    @PostMapping(path = "/excuteAndShow/pagingList")
    @ResponseBody
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public Map<String, Object> pagingList(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        MdmsUser mdmsUser = consoleCommonService.checkAndGetUser(request);

        ExcuteAndShowPagingListData excuteAndShowExecSqlData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(), new TypeReference<>() {
        });

        // 校验传入参数
        Verify.verifyData(excuteAndShowExecSqlData);

        // 正式处理业务
        Map<String, Object> data = excuteAndShowService.pagingList(excuteAndShowExecSqlData, request, mdmsUser);
        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

    /**
     * 导出数据
     */
    @PostMapping(path = "/excuteAndShow/exportData")
    @ResponseBody
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public Map<String, Object> exportData(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        MdmsUser mdmsUser = consoleCommonService.checkAndGetUser(request);
        ExcuteAndShowExportDataData excuteAndShowExportDataData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(),
                new TypeReference<>() {
                });

        // 校验传入参数
        Verify.verifyData(excuteAndShowExportDataData);
        // 正式处理业务
        Map<String, Object> data = excuteAndShowService.exportData(excuteAndShowExportDataData, request, mdmsUser);

        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

    /**
     * 获取导出的数据
     */
    @GetMapping(path = "/excuteAndShow/downloadExportData")
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public String downloadExportData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        consoleCommonService.checkAndGetUser(request);

        String excelName = request.getParameter("excelName");

        cn.hutool.system.UserInfo userInfo = SystemUtil.getUserInfo();
        InputStream in = new FileInputStream(userInfo.getHomeDir() + File.separator + "exportData" + File.separator + excelName);

        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename="
                + excelName);

        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        int size = 0;
        while ((size = in.read(b, 0, b.length)) > 0) {
            os.write(b, 0, size);
        }
        try {
            os.flush();
            os.close();
            in.close();
        } catch (Exception e) {

        } finally {
            File file = new File(userInfo.getHomeDir() + File.separator + "exportData" + File.separator + excelName);
            if (file.exists()) {
                file.delete();
            }
        }

        return null;
    }

    /**
     * 获取常用SQL
     */
    @PostMapping(path = "/excuteAndShow/getCommonSql")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ADMIN','DBA','USER')")
    public Map<String, Object> getCommonSql(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        MdmsUser mdmsUser = consoleCommonService.checkAndGetUser(request);

        ExcuteAndShowGetCommonSqlData excuteAndShowGetCommonSqlData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(), new TypeReference<>() {
        });

        // 校验传入参数
        Verify.verifyData(excuteAndShowGetCommonSqlData);

        // 正式处理业务
        Map<String, Object> data = excuteAndShowService.getCommonSql(excuteAndShowGetCommonSqlData, request, mdmsUser);
        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

    /**
     * 添加常用SQL
     */
    @PostMapping(path = "/excuteAndShow/addCommonSql")
    @ResponseBody
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public Map<String, Object> addCommonSql(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        MdmsUser mdmsUser = consoleCommonService.checkAndGetUser(request);

        ExcuteAndShowAddCommonSqlData excuteAndShowAddCommonSqlData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(),
                new TypeReference<>() {
                });

        // 校验传入参数
        Verify.verifyData(excuteAndShowAddCommonSqlData);

        // 正式处理业务
        Map<String, Object> data = excuteAndShowService.addCommonSql(excuteAndShowAddCommonSqlData, request, mdmsUser);
        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

    /**
     * 编辑常用SQL
     */
    @PostMapping(path = "/excuteAndShow/editCommonSql")
    @ResponseBody
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public Map<String, Object> editCommonSql(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        MdmsUser mdmsUser = consoleCommonService.checkAndGetUser(request);

        ExcuteAndShowEditCommonSqlData excuteAndShowEditCommonSqlData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(),
                new TypeReference<>() {
                });

        // 校验传入参数
        Verify.verifyData(excuteAndShowEditCommonSqlData);

        // 正式处理业务
        Map<String, Object> data = excuteAndShowService.editCommonSql(excuteAndShowEditCommonSqlData, request, mdmsUser);
        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

    /**
     * 删除常用SQL
     */
    @PostMapping(path = "/excuteAndShow/delCommonSql")
    @ResponseBody
    @PreAuthorize("hasAnyRole('DBA','USER')")
    public Map<String, Object> delCommonSql(@RequestBody Map<String, Object> jsonObject, HttpServletRequest request) throws Exception {
        MdmsUser mdmsUser = consoleCommonService.checkAndGetUser(request);

        ExcuteAndShowDelCommonSqlData excuteAndShowDelCommonSqlData = new ObjectMapper().convertValue(new MapForObject(jsonObject).getData(),
                new TypeReference<>() {
                });

        // 校验传入参数
        Verify.verifyData(excuteAndShowDelCommonSqlData);

        // 正式处理业务
        Map<String, Object> data = excuteAndShowService.delCommonSql(excuteAndShowDelCommonSqlData, request, mdmsUser);
        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

}
